package com.ikun.yummy.activitys.details;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.databinding.BindingAdapter;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.ikun.yummy.App;
import com.ikun.yummy.R;
import com.ikun.yummy.activitys.person.PersonActivity;
import com.ikun.yummy.adapter.CommentListAdapter;
import com.ikun.yummy.bean.CommentInfo;
import com.ikun.yummy.bean.CookInfo;
import com.ikun.yummy.bean.FollowInfo;
import com.ikun.yummy.bean.LikeInfo;
import com.ikun.yummy.bean.UserInfo;
import com.ikun.yummy.databinding.ActivityDetailBinding;
import com.ikun.yummy.manager.CommentOpManager;
import com.ikun.yummy.manager.CookOpManager;
//import com.ikun.yummy.manager.FollowOPManager;
import com.ikun.yummy.manager.FollowOPManager;
import com.ikun.yummy.manager.LikeOpManager;
import com.ikun.yummy.manager.UserOpManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import de.hdodenhof.circleimageview.CircleImageView;

public class DetailVM extends AndroidViewModel {
    @SuppressLint("StaticFieldLeak")//防止内存申请detailActivity时，detailActivity外部activity被销毁时
    private static DetailActivity detailActivity;
    private CookOpManager cookOpManager;
    //创建数据监听绑定
    //声明可感知生命周期的变量，方便数据的更新
    public static MutableLiveData<String> coverimg=new MutableLiveData<>();
    public static MutableLiveData<String> userimg=new MutableLiveData<>();
    public static MutableLiveData<String> username=new MutableLiveData<>();
    public static MutableLiveData<String> follow=new MutableLiveData<>();
    public static MutableLiveData<String> cookname=new MutableLiveData<>();
    public static MutableLiveData<String> story=new MutableLiveData<>();
    public static MutableLiveData<String> ingredient=new MutableLiveData<>();
    public static MutableLiveData<String> step=new MutableLiveData<>();
    public static MutableLiveData<String> time=new MutableLiveData<>();
    public static MutableLiveData<String> difficulty=new MutableLiveData<>();
    public static MutableLiveData<String> taste=new MutableLiveData<>();
    public static MutableLiveData<String> classification=new MutableLiveData<>();
    public static MutableLiveData<Boolean> likeImg=new MutableLiveData<>();
    public static MutableLiveData<String> commentCount=new MutableLiveData<>();
    private UserOpManager userOpManager;
    private CookInfo cookInfo;
    private LikeOpManager likeOpManager;
    private CommentListAdapter adp;
    private UserInfo userInfo;
    private CommentOpManager commentOpManager;
    private FollowOPManager followOPManager;

    public DetailVM(@NonNull Application application) {
        super(application);
        coverimg.setValue("");
        username.setValue("");
        userimg.setValue("");
        follow.setValue("关注");
        cookname.setValue("未知菜谱");
        story.setValue("关于菜谱的故事");
        ingredient.setValue("主要食材：");
        time.setValue("");
        difficulty.setValue("");
        taste.setValue("");
        classification.setValue("");
        likeImg.setValue(false);
        step.setValue("");
        commentCount.setValue("评论(0)");
    }
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void setBinding(ActivityDetailBinding binding, DetailActivity detailActivity, String cookid) {
        DetailVM.detailActivity =detailActivity;
        //没登陆也可以进，但不能评论，关注，回复！！！
        cookOpManager=new CookOpManager(detailActivity);
        userOpManager=new UserOpManager(detailActivity);
        likeOpManager=new LikeOpManager(detailActivity);
        commentOpManager=new CommentOpManager(detailActivity);
        followOPManager=new FollowOPManager(detailActivity);
        cookInfo=cookOpManager.queryByCookId(cookid);
        coverimg.setValue(cookInfo.coverimage);
        if (cookInfo.username!=null&&!cookInfo.username.equals("")){
            userimg.setValue(userOpManager.queryUser(cookInfo.username).userimage);
        }
        username.setValue(cookInfo.username);
        cookname.setValue(cookInfo.cookname);
        story.setValue(cookInfo.cookstory);
        try {
            JSONArray ingr=new JSONArray(cookInfo.ingredients);
            StringBuilder ingredients= new StringBuilder();
            for (int i = 0; i < ingr.length(); i++) {
                 ingredients.append(ingr.getString(i)).append(",");
            }
            ingredient.setValue("主要食材："+ingredients);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        time.setValue(cookInfo.time);
        difficulty.setValue(cookInfo.difficulty);
        taste.setValue(cookInfo.taste);
        classification.setValue(cookInfo.classification);
        LikeOpManager likeOpManager=new LikeOpManager(detailActivity);

        step.setValue(cookInfo.step);
        adp=new CommentListAdapter(detailActivity,new ArrayList<>());
        binding.setAdp(adp);
        String user=App.sp.getString("username","null");
        if (!user.equals("null")){
            userInfo = userOpManager.queryUser(user);
            List<LikeInfo> list = likeOpManager.query(cookInfo.cookid, userInfo.username);
            if (list!=null&&list.size()>0){
                likeImg.setValue(true);
            }else{
                likeImg.setValue(false);
            }
        }else{
            userInfo = null;
        }
        refreshComment();
        binding.detailLvComment.setOnItemClickListener((parent, view, position, id) -> {
            if (adp.data.get(position).type==1){//点击评论才可回复
                if (!userInfo.loginstate.equals("1")){
                    Toast.makeText(detailActivity, "请先登录", Toast.LENGTH_SHORT).show();
                    return;
                }
                EditText editText=new EditText(detailActivity);
                editText.setHint("回复"+adp.data.get(position).username);
                AlertDialog.Builder dialog=new AlertDialog.Builder(detailActivity);
                dialog.setTitle("回复").setView(editText).setPositiveButton("确定", (dialog1, which) -> {
                    if (!editText.getText().toString().equals("")){
                        String oldReply=commentOpManager.queryCommentByCommentId(adp.data.get(position).commentid).reply;
                        JSONArray reply;
                        try {
                            reply=new JSONArray(oldReply);
                        } catch (JSONException ignored){
                            reply=new JSONArray();
                        }
                        JSONObject jsonObject=new JSONObject();
                        try {
                            jsonObject.put("username",userInfo.username);
                            jsonObject.put("content",editText.getText().toString());
                            reply.put(jsonObject);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        commentOpManager.updateById(new CommentInfo(2,null,null,reply.toString(),null,null,adp.data.get(position).commentid));
                        refreshComment();
                    }else{
                        Toast.makeText(detailActivity,"请输入内容！",Toast.LENGTH_SHORT).show();
                    }
                }).setNegativeButton("取消",null).setCancelable(false).show();
            }
        });
        //长按删除
        binding.detailLvComment.setOnItemLongClickListener((parent, view, position, id) -> {
            if (adp.data.get(position).type==1){//是评论
                if (adp.data.get(position).username.equals(userInfo.username)||cookInfo.username.equals(userInfo.username)){//我评论的或者我是cook作者
                    AlertDialog.Builder builder = new AlertDialog.Builder(detailActivity);
                    builder.setMessage("确认删除该评论吗？").setTitle("提示").setNeutralButton("取消", null).setPositiveButton("确定", (dialogInterface, i) -> {
                        commentOpManager.deleteCommentByCommentId(adp.data.get(position).commentid);
                        refreshComment();
                    }).show();
                }
            }else{//是回复
                if (adp.data.get(position).username.equals(userInfo.username)||adp.data.get(position).reply.equals(userInfo.username)||cookInfo.username.equals(userInfo.username)){//我回复的或者是在我的评论下回复的或者我是cook作者都可以删
                    AlertDialog.Builder builder = new AlertDialog.Builder(detailActivity);
                    builder.setMessage("确认删除该回复吗？").setTitle("提示").setNeutralButton("取消", null).setPositiveButton("确定", (dialogInterface, i) -> {
//                        commentOpManager.deleteCommentById(adp.data.get(position).commentid);
                        try {
                            JSONArray jsonArray=new JSONArray(commentOpManager.queryCommentByCommentId(adp.data.get(position).reply).reply);

                            for (int j = 0; j < jsonArray.length(); j++) {
                                JSONObject obj = jsonArray.getJSONObject(j);
                                if (obj.getString("username").equals(adp.data.get(position).username)&&obj.getString("content").equals(adp.data.get(position).content)){
                                    //删除这个
                                    jsonArray.remove(j);
                                    //加入剩下的回复到数据库
                                    commentOpManager.updateById(new CommentInfo(0,null,null,jsonArray.toString(),"",null,adp.data.get(position).reply));
                                    break;
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        refreshComment();
                    }).show();
                }
            }
            return true;
        });
        FollowInfo followInfo = followOPManager.queryFollowerSingle(userInfo.username, username.getValue());
        if (followInfo!=null){
            follow.setValue("取关");
        }else{
            follow.setValue("关注");
        }
    }
    /////////绑定事件///////////
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @BindingAdapter("bindCover")
    public static void bindCover(ImageView imageView,MutableLiveData<String> coverimg){
        if (!Objects.equals(coverimg.getValue(), "")){
            File file=new File(Objects.requireNonNull(coverimg.getValue()));
            if (file.exists()){
                imageView.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
            }else {
                imageView.setImageResource(R.drawable.app_logo);
            }
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @BindingAdapter("bindUserImg")
    public static void bindUserImg(CircleImageView imageView, MutableLiveData<String> userimg){
        if (!userimg.getValue().equals("")){
            File file=new File(userimg.getValue());
            if (file.exists()){
                imageView.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
            }else{
                imageView.setImageResource(R.drawable.app_logo);
            }
        }
    }
    @BindingAdapter("bindLike")
    public static void bindLike(ImageView imageView,MutableLiveData<Boolean> likeImg){
        if (likeImg.getValue()){
            imageView.setImageResource(R.mipmap.liked);
        }else{
            imageView.setImageResource(R.mipmap.like);
        }
    }
    @SuppressLint("SetTextI18n")
    @BindingAdapter("bindStep")
    public static void bindStep(LinearLayout linearLayout,MutableLiveData<String> steps){
        linearLayout.removeAllViews();
        try {
            JSONObject jsonObject=new JSONObject(steps.getValue());
            for (int i = 0; i < jsonObject.length(); i++) {
                JSONObject stepBean = jsonObject.getJSONObject("step" + i);
                LinearLayout view;
                if (!stepBean.isNull("img")&&!stepBean.isNull("text")){//有图有文
                    view= (LinearLayout) View.inflate(detailActivity, R.layout.item_detail_step_pic_and_text, null);
                    TextView tv1= (TextView) view.getChildAt(1);
                    tv1.setText(stepBean.getString("text"));
                    ImageView iv= (ImageView) view.getChildAt(2);
                    File file=new File(stepBean.getString("img"));
                    if (file.exists()){
                        iv.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
                    }else{
                        iv.setImageResource(R.drawable.app_logo);
                    }
                }else if (!stepBean.isNull("img")){//仅图
                    view= (LinearLayout) View.inflate(detailActivity, R.layout.item_detail_step_pic, null);
                    ImageView iv= (ImageView) view.getChildAt(1);
                    File file=new File(stepBean.getString("img"));
                    if (file.exists()){
                        iv.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
                    }else{
                        iv.setImageResource(R.drawable.app_logo);
                    }
                }else{
                    view= (LinearLayout) View.inflate(detailActivity, R.layout.item_detail_step_text, null);
                    TextView tv1= (TextView) view.getChildAt(1);
                    tv1.setText(stepBean.getString("text"));
                }
                TextView tv= (TextView) view.getChildAt(0);
                tv.setText("步骤"+(i+1));
                linearLayout.addView(view);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    public void clickFollow(View view){
        if (!userInfo.loginstate.equals("1")){
            Toast.makeText(detailActivity, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }
        if (username.getValue().equals(userInfo.username)){
            Toast.makeText(detailActivity,"不可以关注自己哦",Toast.LENGTH_SHORT).show();
            return;
        }
        FollowInfo followInfo = followOPManager.queryFollowerSingle(userInfo.username, username.getValue());
        if (followInfo!=null){
            follow.setValue("关注");
            Toast.makeText(detailActivity,"已取消关注"+username.getValue(),Toast.LENGTH_SHORT).show();
            followOPManager.delete(userInfo.username,username.getValue());
        }else{
            follow.setValue("取关");
            Toast.makeText(detailActivity,"已关注"+username.getValue(),Toast.LENGTH_SHORT).show();
            followOPManager.insertFollower(new FollowInfo("",userInfo.username,username.getValue(),1));
            followOPManager.insertFollowee(new FollowInfo("",username.getValue(),userInfo.username,1));
        }
    }
    public void clickLike(View view){
        if (userInfo!=null&&userInfo.loginstate.equals("1")){
            List<LikeInfo> list = likeOpManager.query(cookInfo.cookid, userInfo.username);
            String likeid = null;
            if (list!=null){
                for (LikeInfo l :list) {
                    if (l.cookid.equals(cookInfo.cookid)&&userInfo.username.equals(l.username)){
                        likeid=l.likeid;
                        break;
                    }
                }
            }
            if (likeid!=null){
                likeImg.setValue(false);
                likeOpManager.delete(likeid);
            }else{
                likeOpManager.insert(new LikeInfo(cookInfo.cookid,userInfo.username,cookInfo.cookname,cookInfo.cookid));
                likeImg.setValue(true);
                Toast.makeText(detailActivity,"已赞",Toast.LENGTH_SHORT).show();
            }
        }else{
            Toast.makeText(detailActivity,"登陆后才能点赞",Toast.LENGTH_SHORT).show();
        }
    }
    public void addComment(View view){
        if (userInfo!=null&&userInfo.loginstate.equals("1")){
            EditText editText=new EditText(detailActivity);
            editText.setHint("说点什么吧...");
            AlertDialog.Builder dialog=new AlertDialog.Builder(detailActivity);
            dialog.setTitle("评论").setView(editText).setPositiveButton("确定", (dialog1, which) -> {
                if (!editText.getText().toString().equals("")){
                    commentOpManager.addComment(new CommentInfo(1,userInfo.username,editText.getText().toString(),"",userInfo.userimage,cookInfo.cookid,""));
                    refreshComment();
                }else{
                    Toast.makeText(detailActivity,"请输入内容！",Toast.LENGTH_SHORT).show();
                }
            }).setNegativeButton("取消",null).setCancelable(false).show();
        }else{
            Toast.makeText(detailActivity,"登陆后才能评论",Toast.LENGTH_SHORT).show();
        }
    }
    private void refreshComment() {
        adp.data.clear();
        //保证不会返回别的cook的评论
        List<CommentInfo> list = commentOpManager.queryByCookid(cookInfo.cookid);
        if (list!=null){
            commentCount.setValue("评论("+list.size()+")");
            for (CommentInfo co :list) {
                JSONArray reply;
                try {
                    reply=new JSONArray(co.reply);
                } catch (JSONException ignored) {
                    reply=new JSONArray();
                }
                co.userImg= userOpManager.queryUser(co.username).userimage;
                adp.data.add(co);
                if (reply.length()!=0){
                    for (int i = 0; i < reply.length(); i++) {
                        try {
                            JSONObject jsonObject=reply.getJSONObject(i);
                           String img=userOpManager.queryUser(jsonObject.getString("username")).userimage;
                           CommentInfo replyBean=new CommentInfo(2,
                                    jsonObject.getString("username"),
                                    jsonObject.getString("content"),
                                    co.commentid,//注意，reply的reply是评论的commentid，因为reply的reply本没有用，但给reply的reply赋予评论者commentid可以判断删除
                                    img,cookInfo.cookid,
                                    co.commentid);
                            adp.data.add(replyBean);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }else {
            commentCount.setValue("评论(0)");
        }
        adp.notifyDataSetChanged();
    }
    public void personalPage(View view){
        if (userInfo.loginstate.equals("1")){
            if (cookInfo.username.equals(userInfo.username)){
                Intent intent=new Intent();
                intent.putExtra("isMyCook",true);
                detailActivity.setResult(22,intent);
                detailActivity.finish();
            }else{
                Intent intent=new Intent(detailActivity, PersonActivity.class);
                intent.putExtra("username",cookInfo.username);
                detailActivity.startActivity(intent);
            }
        }else{
            Toast.makeText(detailActivity, "请先登录", Toast.LENGTH_SHORT).show();
        }
    }
}